﻿@model RightControl.Model.Translation
@using System.Collections.Generic;
@using RightControl.Model;
@{

    ViewBag.Title = "翻译词库";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutSinglePage.cshtml";
}

@*<blockquote class="layui-elem-quote p10"></blockquote>*@
<div class="layui-form-item">
    <table>
        <tbody>
            <tr>
                <td><label class="layui-form-label">产品图库:</label></td>
                <td>
                    <div class="layui-input-block imgcontainer">
                        <ul class="ulImages" id="imgStore">
                            @{
                                    List<ProductImage> images = ViewData["productImags"] as List<ProductImage>;
                                    if (images != null) {
                                        for (int i = 0; i < images.Count; i++) {
                                            if (images[i].ImgType == 2) {
                                <li id="@images[i].Id">
                                    <div style="position: absolute; ">
                                        <span class="rmPicture close" title="删除此图">×</span>
                                        <img src="@images[i].ImgUrl" />
                                    </div>
                                </li>
                                            }
                                        }
                                    }
                            }
                        </ul>
                        <div class="layui-upload-drag" style="width:85px;height:75px;margin:5px" id="uploadImg">
                            <i class="layui-icon"></i>
                            <p>点击上传或将文件拖到此处</p>
                        </div>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

@*<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>变体信息</legend>
</fieldset>*@
<div class="layui-card-header">变体信息</div>
<div class="layui-fluid">
    <div class="layui-field-box" style="padding:0;">
        <table id="subProductImageTb" lay-filter="defaultruv"></table>
        <script type="text/html" id="bar">
            @Html.ToolBarHtml(ViewData["ActionList"])
        </script>
    </div>
</div>
@*<blockquote class="layui-elem-quote p10"></blockquote>

    <blockquote class="layui-elem-quote p10"></blockquote>*@
<div class="layui-fluid" id="variationTable">
    <div class="layui-field-box" style="padding:0;">
        <table id="subProductTb" lay-filter="subProductruv"></table>
    </div>
</div>

<div class="layui-form-item">
    <div class="layui-input-block">
        <a class="layui-btn" lay-submit="Product/updateProduct" lay-filter="submitForm" id="submitForm">一键保存</a>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
</div>


<div class="layui-fluid" style="min-height: 140px; height: auto;display:none" id="selImgDiv">
    <div class="layui-form-item">
        <ul class="ulImages" id="imgSelect">
            @{
                if (images != null) {
                    for (int i = 0; i < images.Count; i++) {
                        if (images[i].ImgType == 2) {
                            <li id="@images[i].Id">
                                <div style="position: absolute; ">
                                    <input type="checkbox" class="imgCheck" />
                                    <img src="@images[i].ImgUrl" />
                                </div>
                            </li>
                        }
                    }
                }
            }
        </ul>
    </div>
</div>

    <script type="text/javascript" src="~/Areas/Admin/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="~/Areas/Admin/Scripts/jquery-migrate-1.1.1.js"></script>
    <script type="text/javascript" src="~/Areas/Admin/Scripts/jquery.dragsort-0.5.1.min.js"></script>

    <script type="text/javascript">

        layui.use(['table','common','upload','form'], function () {
            var form = layui.form,
                common = layui.common,
                upload = layui.upload //上传
            var $ = layui.$;
            $("#sltIcon").on("click", function () {
                openSetIcon();
            });

            form.render('select');

            try{
                $("#imgStore").dragsort({
                    dragSelector: "img",
                    dragBetween: true ,
                    dragEnd:function(){
                        console.log('此处可放拖动结束后的方法。')
                    }
                });

                $("#imgStore").on("click",".close",function(){
                    $(this).parent().parent().remove();
                });
            }catch(e){
                console.log(e);
            }

            try{
                $("#imgSelect").dragsort({
                    dragSelector: "img",
                    dragBetween: true ,
                    dragEnd:function(){
                        console.log('此处可放拖动结束后的方法。')
                    }
                });

                $("#imgSelect img").on("click",function(){
                    var chkbox = $(this).parent().find("input")[0];
                    chkbox.checked = !chkbox.checked;
                });

            }catch(e){
                console.log(e);
            }

            var updateImages = function(seqId){
                var selectedImage = [];
                var chkboxs = $("#imgSelect").find("input[type=checkbox]:checked");
                if (chkboxs!=null && chkboxs.length>0) {
                    chkboxs.each(function(idx,item){
                        selectedImage.push($(item).parent().find("img").attr("src"));
                    });
                    if (selectedImage.length>0) {
                        layer.load();
                        $.ajax({
                            url: "/Datasrv/SubProduct/UpdateSubProductImages",
                            type: "POST",
                            data: {seqId:seqId,imgUrls:selectedImage.join('^')},
                            dataType: "json",
                            success: function (data) {
                                if (data.state == "success") {
                                    table.reload('subProductImageReload', {});
                                    console.log("图片更新成功")
                                } else {
                                    console.log("图片更新失败")
                                }
                            }
                        });
                        layer.closeAll('loading'); //关闭loading
                    }
                }
            };

            var updateSingleImages = function(imgObj){
                var seqId = imgObj.attr("seqId");
                var idx = imgObj.attr("index");
                var checkedBoxs = $("#imgSelect").find("input[type=checkbox]:checked");
                if (checkedBoxs!=null) {
                    //选中单个校验
                    if (checkedBoxs.length==0 || checkedBoxs.length>1) {
                        layer.alert('请选中一张图片!');
                    }else{
                        var thisBox = $(checkedBoxs[0]);
                        var selectImageUrl = thisBox.parent().find("img").attr("src");
                        if (selectImageUrl.length>0) {
                            layer.load();
                            imgObj.attr("src",selectImageUrl);
                            $.ajax({
                                url: "/Datasrv/SubProduct/UpdateSingleImage",
                                type: "POST",
                                data: {seqId:seqId,imgUrl:selectImageUrl,index:idx},
                                dataType: "json",
                                success: function (data) {
                                    if (data.state == "success") {
                                        console.log("图片更新成功")
                                        thisBox.attr("checked",false)
                                    } else {
                                        console.log("图片更新失败")
                                    }
                                }
                            });
                            layer.closeAll('loading'); //关闭loading
                        }
                    }
                }
            };
            var table = layui.table

            //表格
            table.render({
                id: 'defaultReload'
               , elem: '#subProductTb'
               , minheight: 10 //高度最大化减去差值
               , url: '/DataSrv/SubProduct/GetAllSubProductSizes?productId=@Model.Id&categoryCode=@Model.CategoryCode' //数据接口
               , page: false //开启分页
               , cols: [[ //表头
                         { checkbox: true, fixed: false}
                         ,  { hide: true, title: 'Id', field:'Id' }
                         , { field: 'Size', title: '尺码', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入尺码" value="{{d.Size}}"/></div>', width: 120, align: 'center' }
                          @Html.TabaleHeadHtml(ViewData["TableHead"])
                         , { field: '', title: '操作', templet: '<div><a class="layui-btn layui-btn-xs layui-btn-danger delPrdSize" seqId="{{d.Id}}" lay-event="edit"><i class="layui-icon iconfont icon-guanbi"></i>删除</a></div>' }
               ]]
               ,done: function(res, curr, count){
                   $(".layui-table").on("click",".delPrdSize",function(){
                       var seqId = $(this).attr("seqId");
                       layer.confirm('确定要删除吗？', function (index) {
                           $.ajax({
                               url: "/Datasrv/SubProduct/DeleteSize",
                               type: "POST",
                               data: { "Id": seqId },
                               dataType: "json",
                               success: function (data) {
                                   if (data.state == "success") {
                                       layer.close(index); //关闭弹框
                                       common.msgSuccess("删除成功");
                                       table.reload('defaultReload', {});
                                   } else {
                                       common.msgError("删除失败");
                                   }
                               }
                           });
                       });
                       return false;
                   });
               }
            });
            var $ = layui.$, active = {
                reload: function () {
                    $('#ajax-loader').fadeOut(); //todo：加载滚动条
                    //执行重载
                    table.reload('subProductImageReload', {});

                    table.reload('defaultReload', {});
                }
            };
            //服务器排序
            table.on('sort(defaultruv)', function (obj) {
                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，如：
                table.reload('defaultReload', {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                  , where: { //请求参数
                      field: obj.field //排序字段
                    , order: obj.type //排序方式
                  }
                });
            });

            //监听工具条
            table.on('tool(defaultruv)', function (obj) {
                var data = obj.data;
                if (obj.event === 'detail') {
                    common.openTop({
                        detail: true,
                        title: '操作详情', w: '568px', h: '400px', content: '/Datasrv/Product/Detail/' + data.Id, clickOK: function (index) {
                            common.close(index);
                        }
                    });
                } else if (obj.event === 'del') {
                    layer.confirm('确定要删除吗？', function (index) {
                        $.ajax({
                            url: "/Datasrv/Product/Delete",
                            type: "POST",
                            data: { "Id": data.Id },
                            dataType: "json",
                            success: function (data) {
                                if (data.state == "success") {
                                    obj.del();//删除这一行
                                    layer.close(index); //关闭弹框
                                    common.msgSuccess("删除成功");
                                } else {
                                    common.msgError("删除失败");
                                }
                            }
                        });
                    });
                } else if (obj.event === 'edit') {
                    window.open('/Datasrv/Product/Edit/' + data.Id, "_blank");
                    //location.href = '/Datasrv/Product/Edit/' + data.Id;

                    //common.openTop({
                    //    title: '编辑详情', w: '1600px', h: '780px', content: '/Datasrv/Product/Edit/' + data.Id
                    //});
                }
            });


            table.render({
                id: 'subProductImageReload'
            , elem: '#subProductImageTb'
            , minheight: 10 //高度最大化减去差值
            , url: '/DataSrv/SubProduct/GetAllSubProductImages?productId=@Model.Id' //数据接口
            , page: false //开启分页
            , cols: [[ //表头
                       {type:'checkbox'}
                      , { field: 'Color', title: '颜色', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入颜色" value="{{d.Color}}"/></div>', width: 140, align: 'center' }
                      , { title: '主图', templet: '<div><img seqId="{{d.Id}}" style="width: 50px; height:50px; display: block;cursor:pointer" src="{{d.MainImage}}" index="0"/></div>', width: 80, align: 'center' }
                      , { title: '附属图', templet: '<div class="layui-input-block imgcontainer"><ul class="ulSmallImages" seqId="{{d.Id}}" >'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image01}}" index="1"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image02}}" index="2"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image03}}" index="3"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image04}}" index="4"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image05}}" index="5"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image06}}" index="6"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image07}}" index="7"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image08}}" index="8"/></div></li>'+
                          '<li><div><img seqId="{{d.Id}}" src="{{d.Image09}}" index="9"/></div></li></ul></div>', width: 520, align: 'center' }
                      , { field: '', title: '操作', templet: '<div><a class="layui-btn layui-btn-xs selectBtn" seqId="{{d.Id}}" lay-event="edit"><i class="layui-icon iconfont icon-bianji"></i>选择图片</a>'+
                                                            '<a class="layui-btn layui-btn-xs layui-btn-danger delImg" seqId="{{d.Id}}" lay-event="edit"><i class="layui-icon iconfont icon-guanbi"></i>删除</a></div>' }
            ]]
            ,done: function(res, curr, count){
                $(".layui-table").on("click","img",function(){
                    var imgObj = $(this);
                    layer.open({
                        type: 1,
                        title: '产品图库',
                        area: ['945px', '555px'],
                        content: $('#selImgDiv'),
                        btn: ['取消','确定'],
                        btnAlign: 'r',
                        success: function(layero){
                            var btn = layero.find('.layui-layer-btn');
                            btn.find('.layui-layer-btn1').on("click", function () {
                                updateSingleImages(imgObj);
                            });
                        }
                    });
                    return false;
                });

                $(".layui-table").on("click",".selectBtn",function(){
                    var seqId = $(this).attr("seqId");
                    layer.open({
                        type: 1,
                        title: '产品图库',
                        area: ['945px', '555px'],
                        content: $('#selImgDiv'),
                        btn: ['取消','确定'],
                        btnAlign: 'r',
                        success: function(layero){
                            var btn = layero.find('.layui-layer-btn');
                            btn.find('.layui-layer-btn1').on("click", function () {
                                updateImages(seqId);
                            });
                        }
                    });
                    return false;
                });
                $(".layui-table").on("click",".delImg",function(){
                    var seqId = $(this).attr("seqId");
                    layer.confirm('确定要删除吗？', function (index) {
                        $.ajax({
                            url: "/Datasrv/SubProduct/DeleteColor",
                            type: "POST",
                            data: { "Id": seqId },
                            dataType: "json",
                            success: function (data) {
                                if (data.state == "success") {
                                    layer.close(index); //关闭弹框
                                    common.msgSuccess("删除成功");
                                    table.reload('subProductImageReload', {});
                                } else {
                                    common.msgError("删除失败");
                                }
                            }
                        });
                    });
                    return false;
                });
            }
            });

            $("#submitForm").on("click", function () {
                layer.load(); //loading
                var subProductSizeList = [];
                var subProductRows =  $("#variationTable table tbody tr");
                if (subProductRows!=null) {
                    for (var i = 0; i < subProductRows.length; i++) {
                        var subProdId = $(subProductRows[i]).find('.layui-hide div').text();
                        var inputs = $(subProductRows[i]).find('td input');
                        var keyAttributes="";
                        for (var j = 2; j < inputs.length; j++) {
                            var propVal = $(inputs[j])[0].value;
                            var endStr = j == inputs.length - 1 ? "" : "^";
                            keyAttributes += propVal + endStr;
                        }

                        subProductSizeList.push({
                            Id:subProdId,
                            ProductId:@Model.Id,
                            Size:inputs[1].value,
                            KeyAttributes:keyAttributes});
                    }
                    $.ajax({
                        url: "/Datasrv/SubProduct/UpdateSubProductSizes?categoryCode=@Model.CategoryCode",
                        type: "POST",
                        data: {subProdSizeList:subProductSizeList},
                        dataType: "json",
                        success: function (data) {
                            if (data.state == "success") {
                                common.msgSuccess("更新成功");
                                active['reload'].call(this);
                            } else {
                                common.msgError("更新失败");
                            }
                        }
                    });
                }

                var imgUrls = [];
                $("#imgStore li").each(function(indx,elem){
                    imgUrls.push($(elem).find('img').attr('src'));
                });
                //提交更新图片
                $.ajax({
                    url: "/Datasrv/SubProduct/UpdateImages",
                    type: "POST",
                    data: {productId:@Model.Id,imgUrls:imgUrls.join('^')},
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            console.log("图片更新成功")
                        } else {
                            console.log("图片更新失败")
                        }
                    }
                });
                layer.closeAll('loading'); //关闭loading
            });

            //上传
            upload.render({
                elem: '#uploadImg'
                ,accept:"images"
                ,acceptMime: 'image/*' //只筛选图片
                ,url: '/DataSrv/Product/UploadFiles?productId=@Model.Id&categoryCode=@Model.CategoryCode'//上传接口
                ,progress: function(n){
                    //var percent = n + '%' //获取进度百分比
                    //element.progress('uploadImg', percent); //可配合 layui 进度条元素使用
                }
                ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    layer.load(); //上传loading
                }
                ,done: function(res){
                    if (res!=null&&res.errno==0) {
                        $('#imgStore').append('<li><div style="position: absolute; "><span class="rmPicture close" title="删除此图">×</span><img src="'+ res.data[0]+'" style="cursor: pointer;"></div></li>');
                    }

                    layer.closeAll('loading'); //关闭loading
                    common.msgSuccess("图片上传成功");
                }
                ,error: function(){
                    layer.closeAll('loading'); //关闭loading
                    common.msgSuccess("图片上传异常");
                    //请求异常回调
                }
            });
        });

    </script>





